package com.schoolvisitors.controller.user;

import com.alibaba.fastjson2.JSONObject;
import com.schoolvisitors.dto.UserRegisterDto;
import com.schoolvisitors.response.ResultBody;
import com.schoolvisitors.service.AuthService;
import com.schoolvisitors.service.UserService;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/api/v1/user")
public class AuthController {

    private final AuthService authService;
    private final UserService userService;

    public AuthController(AuthService authService, UserService userService) {
        this.authService = authService;
        this.userService = userService;
    }

    @GetMapping("/auth")
    public ResultBody auth() {
        return ResultBody.success();
    }

    @PostMapping("/register")
    public ResultBody register(@RequestBody @Valid UserRegisterDto userRegisterDto) {
        userService.register(userRegisterDto);
        return ResultBody.success();
    }

    @GetMapping("/weChatAuth")
    public void login(@RequestParam String code, @RequestParam String state, HttpServletRequest request, HttpServletResponse response) throws IOException, IOException {
        log.info("企业微信登录: {} {}", code, state);
        // 调用 authService.auth 方法，获取用户的认证信息
        JSONObject json = authService.auth(code);
        if (json.getString("type").equals("login")) {
            // 设置cookie，例如设置一个名为 "auth_token" 的cookie，存储token
            Cookie cookie = new Cookie("token", json.getString("token"));
            cookie.setPath("/"); // 设置cookie的作用域为整个网站
            //cookie.setHttpOnly(true); // 设置HttpOnly，防止客户端脚本访问cookie
            cookie.setMaxAge(60 * 60 * 24 * 30); // 设置cookie的过期时间，单位为秒（这里是1天）
            //cookie.setSecure(true); // 如果是https请求，可以设置secure为true，保证cookie只有在https连接中才会发送

            // 将cookie添加到响应中
            response.addCookie(cookie);
            response.sendRedirect("https://gwsysyy.sxmu.edu.cn/#/user/auth");
            log.info("老用户");

        } else {
            log.info("新用户需要注册");
            response.sendRedirect("https://gwsysyy.sxmu.edu.cn/#/user/register?token=" + json.getString("token"));

        }
        // 进行重定向
    }

//
//
//    @GetMapping("/getUserInfo")
//    public ResultBody getUserInfo(@Param(value = "userId") Long userId) {
//        UserInfoDto userInfoDto = userService.getUserInfo(userId);
//        return ResultBody.success(userInfoDto);
//    }
}
